package com.evil.common.core.util;

import com.alibaba.fastjson.JSONObject;
import com.evil.common.core.constant.AppConstant;
import com.evil.common.core.entity.TokenInfo;
import com.evil.common.core.enums.RCodeEnum;
import com.evil.common.core.exception.BusinessException;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * @author liyang
 * @date 2023-01-08 12:43
 */
@Component
@AllArgsConstructor
public class TokenUtil {

    private final RedisUtil redisUtil;

    /**
     * 获取token
     *
     * @return TokenInfo
     */
    public TokenInfo getTokenInfo(String token) {
        Object o = redisUtil.get(RedisKeyUtil.accessTokenKey(token));
        TokenInfo tokenInfo = null;
        if (o instanceof TokenInfo) {
            tokenInfo = (TokenInfo) o;
        }
        if (o instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) o;
            tokenInfo = jsonObject.toJavaObject(TokenInfo.class);
        }
        if (null == tokenInfo) {
            throw new BusinessException(RCodeEnum.ERROR_UNAUTHENTICATED);
        }
        return tokenInfo;
    }
}
